﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using YunShop_WebAPI.BLL;
using YunShop_WebAPI.Model;
using static System.Net.Mime.MediaTypeNames;

namespace YunShop_WebAPI.API.Controllers
{
    public class WeiDianController : ApiController
    {

        // 1. 生成授权 URL  例: https://oauth.open.weidian.com/oauth2/authorize?appkey=3703032898&redirect_uri=https://erp6.pos08.com/weidian/callback&response_type=code&state=333
        [HttpPost]
        [HttpGet]
        [ActionName("GenWeiDianAuthUrl")]
        public Result_Model GenWeiDianAuthUrl()
        {
            int userId = CommonFun.ConvertToInt(HttpContext.Current.Request["userId"]);
            string msg = "操作成功!";
            int status = 0;
            //if (userId > 0) ;
            string authURl = WeiDianService.GenWeiDianAuthUrl(userId.ToString());
            status = 1;
            return new Result_Model(status, msg, authURl);
        }


        /// <summary>
        /// 2. 授权后的回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("Callback")]
        public async Task<Result_Model> Callback(string code = "", string state = "")
        {

            string msg = "用户授权成功!";
            int status = 0;
            if (string.IsNullOrWhiteSpace(code))
            {
                msg = "用户拒绝授权";
            }
            // 根据自定的state 查询对应商家,然后通过code获取token  ,把AccessToken 和refresh_token存起来
            SystemInfo.WriteInterfaceLog("WeiDianCallBack", $"code={code},state={state}", "1", "1A", DBHelper.ConnMaster);
            WeiDianService.SaveWeiDianAuthUrl(code, CommonFun.ConvertToInt(state));
            WeiDianAccessTokenResp resp = await WeiDianService.GetWeiDianAccessToken(code);
            status = 1;
            var data = new
            {
                code,
                state
            };
            // 正式环境请注释 data
            return new Result_Model(status, msg, null);
        }

        /// <summary>
        /// 3.获取token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("GetWeiDianAccessToken")]
        public async Task<Result_Model> GetWeiDianToken()
        {
            string m_code = CommonFun.ConvertToString(HttpContext.Current.Request["code"]);

            string msg = "操作成功!";
            int status = 0;
            WeiDianAccessTokenResp resp = await WeiDianService.GetWeiDianAccessToken(m_code);
            status = 1;

            return new Result_Model(status, msg, resp);
        }

        /// <summary>
        /// 4.刷新token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("RefreshWeiDianToken")]
        public async Task<Result_Model> RefreshWeiDianToken()
        {
            string m_refreshToken = CommonFun.ConvertToString(HttpContext.Current.Request["refreshToken"]);
            string msg = "操作成功!";
            WeiDianAccessTokenResp resp = await WeiDianService.RefreshWeiDianTokenAsync(m_refreshToken);
            int status = 0;
            return new Result_Model(status, msg, resp);
        }

        // 4.定时刷新所有token
        [HttpPost]
        [HttpGet]
        [ActionName("RefreshWeiDianTokenAll")]
        public async Task<Result_Model> RefreshWeiDianTokenAll()
        {
            string msg = "操作成功!";
            var reslut = await WeiDianService.RefreshWeiDianTokenAll();
            int status = 0;
            return new Result_Model(status, msg, reslut);
        }
                        
        /// <summary>
        /// 5.同步所有更新的商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("SyncGoodsToWeiDian")]
        public async Task<Result_Model> SyncGoodsToWeiDian()
        {
            int corpId = CommonFun.ConvertToInt(HttpContext.Current.Request["corpId"]);
            int status = 0;

            if (corpId <= 0)
            {
                return new Result_Model(status, "corpId为空");
            }
            string msg = "操作成功!";
            var data = await WeiDianService.SyncGoodsToWeiDian(corpId);
            status = 1;
            return new Result_Model(status, msg, data);
        }

        /// <summary>
        /// 6. 订单推送
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [ActionName("PushOrder")]
        public async Task<dynamic> PushOrder(string content ="")
        {
            string msg = "用户授权成功!";
            SystemInfo.WriteInterfaceLog("PushOrder", $"content={content}", "1", "1A", DBHelper.ConnMaster);
            Stream xmlStream = System.Web.HttpContext.Current.Request.InputStream;
            StreamReader rd = new StreamReader(xmlStream);
            string json = rd.ReadToEnd();
            string data = System.Web.HttpUtility.UrlDecode(json, System.Text.Encoding.UTF8);
            SystemInfo.WriteInterfaceLog("PushOrder", $"json={data}", "2", "2A", DBHelper.ConnMaster);

            string status = await WeiDianService.PushOrder(data);

            //string status = "success";
            return new ResultWeiDian(status);
        }

    }
}